<template>
  <PublicLoading v-if="loading.mounted" />
  <div class="dt-main-tabs-content" v-else>
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <div class="dt-head-title">
            <div class="dt-detail-title">{{orgName}}</div>
          </div>
        </div>
      </div>
      <div class="dt-content-page">
        <div class="dt-add-org" @click="showTotal" v-if="!groupId">
          <i class="el-icon-circle-plus-outline"></i>
          <span>添加单位总群</span>
        </div>
        <div class="dt-org" v-if="org">
          <PcComOrgTree ref="orgTree" :nodes="org" @showDepart="showDepart" @showEdit="showEdit" />
        </div>
      </div>
      <div class="dt-content-bottom">
        <el-button type="primary" @click="goChat">返 回</el-button>
      </div>
    </div>
    <el-dialog :title="totalForm.isEdit?'编辑总群':'添加总群'" :visible.sync="dialogVisible.total" width="680px" :close-on-click-modal="false"
      :append-to-body="true" @close="closeForm('total')">
      <el-form :model="totalForm" :rules="totalRules" ref="totalForm" label-width="100px" :validate-on-rule-change="false">
        <el-form-item label="总群名称" prop="groupName" size="medium">
          <el-input placeholder="请输入总群名称" v-model="totalForm.groupName" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="群主" prop="groupUid" size="medium">
          <!--团队成员、外部成员-->
          <!-- <PublicSelectCompanyUser :option="totalManagerOpt" @select="selectUser($event,'totalManager')" :disabled="true" /> -->
          <el-select v-model="uid" disabled style="width:100%">
            <el-option :label="uname" :value="uid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人" prop="joinUids" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectOutUser :option="totalJoinerOpt" @select="selectUser($event,'totalJoiner')" />
        </el-form-item>
        <el-form-item label="" size="medium">
          <el-button type="primary" @click="sureEdit('total')" :loading="loading.total" v-if="totalForm.isEdit">确定</el-button>
          <el-button type="primary" @click="sureAdd('Total')" :loading="loading.total" v-else>确定</el-button>
          <el-button @click="closeForm('total')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :title="departForm.isEdit?'编辑子群':'添加子群'" :visible.sync="dialogVisible.depart" width="680px" :close-on-click-modal="false"
      :append-to-body="true" @close="closeForm('depart')">
      <el-form :model="departForm" :rules="departRules" ref="departForm" label-width="100px" :validate-on-rule-change="false">
        <el-form-item label="子群名称" prop="groupName" size="medium">
          <el-input placeholder="请输入子群名称" v-model="departForm.groupName" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="群主" prop="groupUid" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectOutUser :option="departManagerOpt" @select="selectUser($event,'departManager')" />
        </el-form-item>
        <el-form-item label="参与人" prop="joinUids" size="medium">
          <!--团队成员、外部成员-->
          <PublicSelectOutUser :option="departJoinerOpt" @select="selectUser($event,'departJoiner')" />
        </el-form-item>
        <el-form-item label="" size="medium">
          <el-button type="primary" @click="sureEdit('depart')" :loading="loading.depart" v-if="departForm.isEdit">确定</el-button>
          <el-button type="primary" @click="sureAdd('Depart')" :loading="loading.depart" v-else>确定</el-button>
          <el-button @click="closeForm('depart')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      org: null, //总群组织架构
      loading: { mounted: false, total: false, depart: false },
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      uname: decodeURIComponent(this.$store.state.uname),
      currgroupId: '', //编辑用
      dialogVisible: {
        total: false,
        depart: false
      },
      //总群
      totalForm: {
        isEdit: false,
        groupName: '',
        groupUid: [], //创建时候不用
        joinUids: []
      },
      totalRules: {
        groupName: [{ required: true, message: '请输入总群名称', trigger: 'blur' }],
        groupUid: [{ required: true, message: '请选择群主', trigger: 'change' }]
        //  joinUids: [{ required: true, message: '请选择参与', trigger: 'change' }]
      },
      //总群-群主的选人配置
      totalManagerOpt: {
        width: '540px',
        placeholder: '请选择群主，最多设置1人',
        isMultiple: false, //是否多选
        isMaster: false, //是否群主
        maxSelect: 1, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //总群-参与人的选人配置
      totalJoinerOpt: {
        width: '540px',
        placeholder: '请选择参与人',
        isMultiple: true, //是否多选
        isMaster: false, //是否群主
        maxSelect: 499, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //子群
      departForm: {
        isEdit: false,
        parentId: '', //从递归组件回传
        groupName: '',
        groupUid: [],
        joinUids: []
      },
      departRules: {
        groupName: [{ required: true, message: '请输入子群名称', trigger: 'blur' }],
        groupUid: [{ required: true, message: '请选择群主', trigger: 'change' }]
        // joinUids: [{ required: true, message: '请选择参与', trigger: 'change' }]
      },
      //总群-群主的选人配置
      departManagerOpt: {
        width: '540px',
        placeholder: '请选择群主，最多设置1人',
        isMultiple: false, //是否多选
        isMaster: true, //是否群主
        maxSelect: 1, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      },
      //总群-参与人的选人配置
      departJoinerOpt: {
        width: '540px',
        placeholder: '请选择参与人',
        isMultiple: true, //是否多选
        isMaster: false, //是否群主
        maxSelect: 499, //单选忽略
        //已选的成员列表
        selectedUserList: [],
        //团队成员列表
        companyUserList: []
      }
    }
  },
  computed: {
    query() {
      return this.$tools.getQuery(this)
    },
    elTab() {
      return this.$tools.getQuery(this).elTab
    },
    groupId() {
      return this.$tools.getQuery(this).groupId || ''
    },
    orgName() {
      return this.elTab === '0' ? '新建高级群聊' : '编辑群组织架构'
    }
  },
  methods: {
    //获取团队成员列表
    getCompanyUserList() {
      var data = [{ userId: this.uid }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/companyUserList'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              //总群成员列表赋值 排除当前登录人（创建人）
              this.totalManagerOpt.companyUserList = data.data.filter((item) => {
                return item.userId != this.uid
              })
              this.totalJoinerOpt.companyUserList = data.data.filter((item) => {
                return item.userId != this.uid
              })
              //子群成员列表赋值 排除当前登录人（创建人）
              this.departManagerOpt.companyUserList = data.data.filter((item) => {
                return item.userId != this.uid
              })
              this.departJoinerOpt.companyUserList = data.data.filter((item) => {
                return item.userId != this.uid
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //获取总群组织架构
    getOrg(groupId) {
      var data = [{ userId: this.uid, groupId: groupId }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/customGroup/groupOrgStructure'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.org = data.data
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    //确认添加
    sureAdd(type) {
      this.$refs[type.toLowerCase() + 'Form'].validate((valid) => {
        if (valid) {
          this.loading[type.toLowerCase()] = true
          this['add' + type]()
        }
      })
    },
    //重置表单和选人组件
    closeForm(type) {
      this.dialogVisible[type] = false
      //重置
      this[type + 'Form'].groupName = ''
      this[type + 'Form'].groupUid = []
      this[type + 'Form'].joinUids = []
      this[type + 'ManagerOpt'].selectedUserList = []
      this[type + 'JoinerOpt'].selectedUserList = []
      //清空验证
      this.$nextTick(() => {
        this.$refs[type + 'Form'].clearValidate()
      })
    },
    //管理单位、合作单位、专业选人后回调
    selectUser(ids, type) {
      //console.log(ids, type)
      switch (type) {
        // case 'totalManager':
        //   this.totalForm.groupUid = ids
        //   break
        case 'totalJoiner':
          this.totalForm.joinUids = ids
          break
        case 'departManager':
          this.departForm.groupUid = ids
          break
        case 'departJoiner':
          this.departForm.joinUids = ids
          break
      }
    },
    //添加总群弹窗
    showTotal() {
      this.dialogVisible.total = true
      this.totalForm.isEdit = false
      this.totalForm.groupName = ''
      this.totalForm.groupUid = [{ userId: this.uid, enableHistoryMsg: '1' }] //创建时候不用
      this.totalForm.joinUids = []
    },
    //添加总群
    addTotal() {
      var data = [{ userId: this.uid, groupName: this.totalForm.groupName, joinUids: JSON.stringify(this.totalForm.joinUids) }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/customGroup/createSeniorGroup'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1500',
                onClose: () => {
                  this.loading.total = false
                  this.dialogVisible.total = false
                  this.org = data.data
                  this.$router.push('/main/#/pc?tab=org&elTab=0&groupId=' + data.data.id)
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1500',
                onClose: () => {
                  this.loading.total = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    //添加子群弹窗
    showDepart(parentId) {
      this.dialogVisible.depart = true
      this.departForm.isEdit = false
      this.departForm.parentId = parentId
      this.departForm.groupName = ''
      this.departForm.groupUid = []
      this.departForm.joinUids = []
    },
    //添加子群
    addDepart() {
      var data = [
          {
            parentId: this.departForm.parentId,
            userId: this.uid,
            groupName: this.departForm.groupName,
            groupUid: JSON.stringify(this.departForm.groupUid[0]),
            joinUids: this.departForm.joinUids ? JSON.stringify(this.departForm.joinUids) : ''
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/customGroup/createSonGroup'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading.depart = false
                  this.dialogVisible.depart = false
                  this.org = data.data
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading.depart = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    /***************************编辑部分******************************/
    //获取群信息
    getGroupInfo(parentId, groupId) {
      var data = [{ userId: this.uid, groupId: groupId }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/customGroup/groupCardInfo'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              //将createForm 转为 editForm
              this.currgroupId = data.data.id
              if (parentId === 0) {
                //总群
                this.dialogVisible.total = true
                this.totalForm.isEdit = true
                this.totalForm.groupName = data.data.groupName
                // 已选群主列表
                this.totalManagerOpt.selectedUserList = data.data.userList.filter((item) => {
                  return item.userRole === 1
                })
                this.totalForm.groupUid = this.totalManagerOpt.selectedUserList.map((item) => {
                  return { userId: item.userId, enableHistoryMsg: item.enableHistoryMsg }
                })

                //已选参与人列表
                this.totalJoinerOpt.selectedUserList = data.data.userList.filter((item) => {
                  return item.userRole === 2 || item.userRole === 3
                })
                this.totalForm.joinUids = this.totalJoinerOpt.selectedUserList.map((item) => {
                  return { userId: item.userId, enableHistoryMsg: item.enableHistoryMsg }
                })
              } else {
                //子群
                this.dialogVisible.depart = true
                this.departForm.isEdit = true
                this.departForm.groupName = data.data.groupName
                // 已选群主列表
                this.departManagerOpt.selectedUserList = data.data.userList.filter((item) => {
                  return item.userRole === 1
                })
                this.departForm.groupUid = this.departManagerOpt.selectedUserList.map((item) => {
                  return { userId: item.userId, enableHistoryMsg: item.enableHistoryMsg }
                })

                //已选参与人列表
                this.departJoinerOpt.selectedUserList = data.data.userList.filter((item) => {
                  return item.userRole === 2 || item.userRole === 3
                })
                this.departForm.joinUids = this.departJoinerOpt.selectedUserList.map((item) => {
                  return { userId: item.userId, enableHistoryMsg: item.enableHistoryMsg }
                })
              }
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    showEdit(parentId, groupId) {
      this.getGroupInfo(parentId, groupId)
    },
    //确认编辑
    sureEdit(type) {
      this.$refs[type + 'Form'].validate((valid) => {
        if (valid) {
          this.loading[type] = true
          this.editGroup(type)
        }
      })
    },
    //编辑高级群
    editGroup(type) {
      var data = [
          {
            userId: this.uid,
            groupId: this.currgroupId,
            groupName: this[type + 'Form'].groupName,
            groupUid: JSON.stringify(this[type + 'Form'].groupUid[0]),
            joinUids: JSON.stringify(this[type + 'Form'].joinUids)
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/customGroup/editSeniorGroup'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                duration: '1000',
                onClose: () => {
                  this.loading[type] = false
                  this.dialogVisible[type] = false
                  this.org = data.data
                }
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                duration: '1000',
                onClose: () => {
                  this.loading[type] = false
                  // this.dialogVisible[type] = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    /*************/
    goChat() {
      this.$router.push('/main/#/pc?tab=chat&groupId=' + this.groupId)
      if (this.elTab === '0') {
        //新建组织架构返回时关闭
        this.$tools.setTabs(this, this.secret_uid, 'close', { hashName: 'pc-org' })
      }
    }
  },
  mounted() {
    if (this.groupId) {
      this.getOrg(this.groupId)
    }
    this.getCompanyUserList()
  }
}
</script>
<style scoped>
.dt-content-page {
  background-color: transparent;
}
.dt-add-org {
  width: 320px;
  height: 97px;
  line-height: 97px;
  text-align: center;
  background-color: #fff;
  border: 1px solid #e9eef7;
  cursor: pointer;
}
.dt-add-org i {
  color: #909399;
}
.dt-add-org span {
  color: #909399;
  font-size: 12px;
}
.dt-add-org:hover {
  background-color: #f0f5ff;
  border-color: #d6e4ff;
}
.dt-add-org:hover i,
.dt-add-org:hover span {
  color: #2f54eb;
}
/*弹窗样式*/
.el-dialog__wrapper >>> .el-dialog__header {
  padding: 18px 20px 16px;
}
.el-dialog__wrapper >>> .el-dialog__body {
  padding: 0 20px 16px;
}
.el-dialog__wrapper >>> .el-form-item__label {
  text-align: left;
}
.el-dialog__wrapper >>> .el-form .el-form-item:nth-last-child(1) {
  text-align: right;
  padding: 16px 20px 0 20px;
  border-top: 1px solid #e9eef7;
  margin: 0 -20px;
}
</style>